<template>
  <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="套餐名称" prop="healthName">
        <el-input v-model="form.healthName" style="width: 400px" />
      </el-form-item>
      <el-form-item label="套餐介绍" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item label="套餐折扣" prop="discount">
        <el-input v-model="form.discount" style="width: 50px" />
      </el-form-item>
      <!-- 套餐产品 -->
      <el-form-item label="套餐产品">
        <div class="product-options-container">
          <div v-for="(product, index) in form.productHealthItems" :key="index" class="product-item">
            <el-select
                v-model="product.bigTypeId"
                placeholder="选择大类"
                @change="handleBigTypeChange(index)"
                style="width: 150px"
            >
              <el-option
                  v-for="item in bigTypeSelectOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
            <el-select
                v-model="product.smallTypeId"
                placeholder="选择小类"
                @change="handleSmallTypeChange(index)"
                style="width: 150px; margin-left: 10px;"
            >
              <el-option
                  v-for="item in smallTypeSelectOptions[index]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
            <el-select
                v-model="product.goodId"
                placeholder="选择商品"
                style="width: 150px; margin-left: 10px;"
            >
              <el-option
                  v-for="item in productOptions[index]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
            <el-button
                type="danger"
                @click="removeProductOption(index)"
                style="margin-left: 10px;"
            >
              移除
            </el-button>
          </div>
          <div class="add-product-button">
            <el-button type="primary" @click="addProductOption">添加产品</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch, nextTick } from "vue";
import axios from "@/util/axios";
import { ElMessage } from "element-plus";

const props = defineProps({
  id: { type: Number, default: -1, required: true },
  dialogTitle: { type: String, default: "", required: true },
  dialogVisible: { type: Boolean, default: false, required: true },
});

const emit = defineEmits(["update:modelValue", "initProductHealthList"]);

const form = ref({
  id: -1,
  healthName: "",
  description: "",
  discount: "",
  productHealthItems: [],
});

const bigTypeSelectOptions = ref([]);
const smallTypeSelectOptions = ref([]);
const productOptions = ref([]);

const formRef = ref(null);

const rules = ref({
  healthName: [{ required: true, message: "请输入套餐名称", trigger: "blur"}],
  description: [{ required: true, message: "请输入套餐描述", trigger: "blur" }],
  discount: [{ required: true, message: "请输入套餐折扣" , trigger: "blur"}],
});

const initBigTypeSelectList = async () => {
  const res = await axios.get("admin/bigType/listAll");
  bigTypeSelectOptions.value = res.data.bigTypeList;
};

const initSmallTypeSelectList = async (bigTypeId, index) => {
  const res = await axios.get(`admin/smallType/listAll/${bigTypeId}`);
  smallTypeSelectOptions.value[index] = res.data.smallTypeList || [];
  // 设置默认小类和商品
  if (form.value.productHealthItems[index].smallTypeId) {
    await initProductOptions(form.value.productHealthItems[index].smallTypeId, index);
  }
};

const initProductOptions = async (smallTypeId, index) => {
  const res = await axios.get(`admin/product/listAll/${smallTypeId}`);
  productOptions.value[index] = res.data.productList || [];
};

watch(
    () => props.dialogVisible,
    async (visible) => {
      if (visible) {
        resetForm();
        await nextTick(() => formRef.value?.clearValidate()); // 清除校验状态
        await initBigTypeSelectList();
        if (props.id !== -1) {
          const res = await axios.get(`admin/productHealth/${props.id}`);
          if (res.data.code === 0) {
            const productHealth = res.data.productHealth;
            form.value = {
              id: productHealth.id,
              healthName: productHealth.healthName,
              description: productHealth.description,
              discount: productHealth.discount,
              image: productHealth.image,
              isHot: productHealth.isHot,
              productHealthItems: productHealth.productHealthItems.map((item) => ({
                bigTypeId: item.product.type.bigType.id,
                smallTypeId: item.product.type.id,
                goodId: item.goodId,
              })),
            };
            await Promise.all(
                form.value.productHealthItems.map(async (item, index) => {
                  await initSmallTypeSelectList(item.bigTypeId, index);
                })
            );
          } else {
            ElMessage.error("加载数据失败！");
          }
        }
      }
    }
);

const addProductOption = () => {
  form.value.productHealthItems.push({
    bigTypeId: "",
    smallTypeId: "",
    goodId: "",
  });
  smallTypeSelectOptions.value.push([]);
  productOptions.value.push([]);
};

const removeProductOption = (index) => {
  form.value.productHealthItems.splice(index, 1);
  smallTypeSelectOptions.value.splice(index, 1);
  productOptions.value.splice(index, 1);
};

const resetForm = () => {
  form.value = {
    id: -1,
    healthName: "",
    description: "",
    discount: "",
    productHealthItems: [],
  };
  smallTypeSelectOptions.value = [];
  productOptions.value = [];
};

const handleBigTypeChange = (index) => {
  initSmallTypeSelectList(form.value.productHealthItems[index].bigTypeId, index);
};

const handleSmallTypeChange = (index) => {
  initProductOptions(form.value.productHealthItems[index].smallTypeId, index);
};

const handleClose = () => {
  resetForm();
  emit("update:modelValue", false);
};

const handleConfirm = async () => {

  const valid = await formRef.value.validate();
  if (valid) {
    const res = await axios.post("admin/productHealth/save", form.value);
    if (res.data.code === 0) {
      ElMessage.success("保存成功！");
      emit("initProductHealthList");
      handleClose();
    } else {
      ElMessage.error(res.data.msg);
    }
  }
};
</script>

<style scoped>
.product-options-container {
  flex-direction: column;
  gap: 15px;
}
.product-item {
  margin: 5px;
  align-items: center;
}
.add-product-button {
  margin-top: 5px;
  text-align: left;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
